package com.example.market2023.service;

import com.example.market2023.dao.GoodsDao;
import com.example.market2023.entity.Goods;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class GoodsService implements GoodsDao {

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Override
    public int add(Goods goods) {
        String sql="insert into goods values(null,?,?,?,?,?,'0')";
        Object[] args={goods.getName(),goods.getPrice(),goods.getQuantity(),goods.getCategory(),goods.getSupplier()};
        return jdbcTemplate.update(sql,args);
    }

    /**
     * 删除操作
     * @param goods
     * @return
     */
    @Override
    public int delete(Goods goods) {
        String sql="delete from goods where Id=?";
        Object[] args={goods.getId()};
        return jdbcTemplate.update(sql,args);
    }

    /**
     * 更新商品操作
     * @param goods
     * @return
     */
    @Override
    public int update(Goods goods) {
        String sql ="update goods set name=?,price=?,quantity=?,category=?,supplier=? where Id=?";
        Object[] args={
                goods.getName(),goods.getPrice(), goods.getQuantity(),
                goods.getCategory(),goods.getSupplier(),goods.getId()
        };
        return jdbcTemplate.update(sql,args);
    }

    @Override
    public Goods findOne(Goods goods) {
        String sql="select * from goods where Id="+goods.getId().toString();
        return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Goods>(Goods.class));
    }

    @Override
    public List<Goods> findAll() {
        String sql = "select * from goods";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<Goods>(Goods.class));
    }
}

